package com.africanmoviesmobile.ui;

import java.io.IOException;

import org.pixmob.httpclient.HttpClientException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.africanmoviesmobile.R;
import com.africanmoviesmobile.webservice.AmmWebService;
import com.africanmoviesmobile.webservice.BasicAsyncCallback;
import com.africanmoviesmobile.webservice.WebServiceException;
import com.africanmoviesmobile.webservice.inf.User;
import com.africanmoviesmobile.webservice.inf.WebserviceObject;

public class LoginActivity extends BaseActivity implements OnClickListener {

	private ProgressDialog mProgressDialog;
	
	private Button mLoginButton;
	private Button mRegisterButton;
	private TextView mForgetPassword;
	
	AmmWebService mAmmWebService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		//check if the user has already logged in
    	if(getLoginEmail() != null){
    		startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    	}
		
    	super.onCreate(savedInstanceState);
    	
		setContentView(R.layout.login_activity);
		
		ActionBar actionBar = getSupportActionBar();
		
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_actionbar_bg));
		actionBar.setHomeButtonEnabled(false);
		
		getWindow().setBackgroundDrawableResource(R.drawable.login_activity_bg);
		
		mLoginButton = (Button) findViewById(R.id.login_button);
		mLoginButton.setOnClickListener(this);
		
		mRegisterButton = (Button) findViewById(R.id.register_button);
		mRegisterButton.setOnClickListener(this);
		
		mForgetPassword = (TextView) findViewById(R.id.forget_password);
		mForgetPassword.setOnClickListener(this);
		
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setCancelable(false);
		mProgressDialog.setMessage("Please wait...");
		
		mAmmWebService = AmmWebService.getInstance(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	protected void onResume() {
		//check if the user has already logged in
    	if(getLoginEmail() != null){
    		startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    	}
    	
		super.onResume();
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		
		case R.id.login_button:
				LoginUserDialogFragment loginUserDialogFragment = new LoginUserDialogFragment();
				loginUserDialogFragment.setRetainInstance(true);
				loginUserDialogFragment.show(getSupportFragmentManager(), "login_user");	
			break;
			
		case R.id.register_button:
			    RegisterUserDialogFragment registerUserDialogFragment = new RegisterUserDialogFragment();
			    registerUserDialogFragment.setRetainInstance(true);
			    registerUserDialogFragment.show(getSupportFragmentManager(), "register_user");				
				break;
				
		case R.id.forget_password:
			ForgetPasswordDialogFragment forgetPasswordDialogFragment = new ForgetPasswordDialogFragment();
			forgetPasswordDialogFragment.setRetainInstance(true);
			forgetPasswordDialogFragment.show(getSupportFragmentManager(), "forget_password");				
			break;		
			
		}
		
	}
	
	@SuppressLint("ValidFragment")
	public class LoginUserDialogFragment extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            
        	final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View loginUserLayout = inflater.inflate(R.layout.login_user, null);
            
            final TextView emailTextView = (TextView) loginUserLayout.findViewById(R.id.email);
            final TextView passwordTextView = (TextView) loginUserLayout.findViewById(R.id.password);
            
            builder.setView(loginUserLayout)
            	   .setTitle(R.string.login)
            	   .setPositiveButton(R.string.login, null)
	               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                    	   LoginUserDialogFragment.this.getDialog().cancel();
                       }
                   });
            
            AlertDialog dialog = builder.create();
            
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
			    @Override
			    public void onShow(final DialogInterface dialog) {
			        Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
			        button.setOnClickListener(new View.OnClickListener() {
			            @Override
			            public void onClick(View view) {
			            	
			            	//check if the user has already logged in
			            	if(getLoginEmail() != null){
			            		
			            		runOnUiThread(new Runnable() {public void run() { 
        							dialog.dismiss();
        							startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    							}});
			            		
			            	}else{
			            		
			            		mProgressDialog.show();
			        			
			        			mAmmWebService.authenticateUser(emailTextView.getText().toString(), passwordTextView.getText().toString(), new BasicAsyncCallback() {

			        				public void onComplete(final boolean[] result, final Object state) {

			        					boolean response = (boolean) result[0];
			        					
			        					if(response){
			        						
			        						User userInfo = null;
			        						
			        						try {
			        							userInfo = (User) mAmmWebService.getUser(emailTextView.getText().toString());
			        						} catch (HttpClientException e) {
			        							Log.w("AMM HttpClientException:", e.getMessage());
			        						} catch (IOException e) {
			        							Log.w("AMM IOException:", e.getMessage());
			        						} catch (WebServiceException e) {
			        							Log.w("AMM WebServiceException:", e.getMessage());
			        						}
			        						
			        						if(userInfo != null){
			        							
			        							final String name = userInfo.getName();
			        							
			        							runOnUiThread(new Runnable() {public void run() { 
			        								
			        								mProgressDialog.dismiss();
			        								
				        							dialog.dismiss();
				        							
				        							//set user session
				        							SharedPreferences.Editor editor = mPrefsUserLogin.edit();
				        						    editor.putString("email", emailTextView.getText().toString());
				        						    editor.putString("name", name);
				        						    editor.commit();
				        						    
				        							startActivity(new Intent(LoginActivity.this, HomeActivity.class));
				        							
			        							}});
			        							
			        						}else{
			        							runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
			        							alertMessage(R.string.login_error);
			        						}
			        						
			        						
			        						
			        					}else{
			        						runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
			        						alertMessage(R.string.invalid_login);
			        					}
			        				}

			        				public void onHttpClientException(final HttpClientException e, final Object state) {
			        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
			        					Log.w("AMM HttpClientException:", e.getMessage());
			        				}
			        				
			        				public void onIOException(final IOException e, final Object state) {
			        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
			        					Log.w("AMM IOException:", e.getMessage());
			        				}

			        				public void onWebServiceException(final WebServiceException e, final Object state) {
			        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
			        					Log.w("AMM WebServiceException:", e.getMessage());
			        					alertMessage(R.string.login_error);
			        				}

			        			}, null);
			            	}
			            }
			        });
			    }
			});
            
            return dialog;
        }
    }
	
	@SuppressLint("ValidFragment")
	public class RegisterUserDialogFragment extends DialogFragment {
	        @Override
	        public Dialog onCreateDialog(Bundle savedInstanceState) {
	            
	        	final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
	            
	            LayoutInflater inflater = getActivity().getLayoutInflater();
	            View registerUserLayout = inflater.inflate(R.layout.register_user, null);
	            
	            final TextView fullNameTextView = (TextView) registerUserLayout.findViewById(R.id.full_name);
	            final TextView emailTextView = (TextView) registerUserLayout.findViewById(R.id.email);
	            final TextView retypeEmailTextView = (TextView) registerUserLayout.findViewById(R.id.retype_email);
	            final TextView passwordTextView = (TextView) registerUserLayout.findViewById(R.id.password);
	            final TextView retypePasswordTextView = (TextView) registerUserLayout.findViewById(R.id.retype_password);
	            
	            builder.setView(registerUserLayout)
         	   		   .setTitle(R.string.register)
	            	   .setPositiveButton(R.string.register, null)
		               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	                       public void onClick(DialogInterface dialog, int id) {
	                    	   RegisterUserDialogFragment.this.getDialog().cancel();
	                       }
	                   });
	            
	            AlertDialog dialog = builder.create();
	            
	            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
				    @Override
				    public void onShow(final DialogInterface dialog) {
				        Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
				        button.setOnClickListener(new View.OnClickListener() {
				            @Override
				            public void onClick(View view) {
				            	
				            	if((fullNameTextView.length() == 0) || (!fullNameTextView.getText().toString().matches("[a-zA-Z ]+"))){
				            		fullNameTextView.setError(getResources().getString(R.string.invalid_name));
		                   			}else if((emailTextView.length() == 0) || (android.util.Patterns.EMAIL_ADDRESS.matcher(emailTextView.getText().toString()).matches() == false)){
		                   				emailTextView.setError(getResources().getString(R.string.invalid_email));
		                   				}else if (emailTextView.getText().toString().compareToIgnoreCase(retypeEmailTextView.getText().toString()) != 0) {
		                   					retypeEmailTextView.setError(getResources().getString(R.string.retype_email_unmatched));
										}else if ((passwordTextView.length() == 0)) {
											passwordTextView.setError(getResources().getString(R.string.invalid_password));
										}else if (passwordTextView.getText().toString().compareToIgnoreCase(retypePasswordTextView.getText().toString()) != 0) {
											retypePasswordTextView.setError(getResources().getString(R.string.retype_password_unmatched));
										}else{

											mProgressDialog.show();
											
		        							//set user session
		        							SharedPreferences.Editor editor = mPrefsUserLogin.edit();
		        						    editor.putString("email", emailTextView.getText().toString());
		        						    editor.putString("name", fullNameTextView.getText().toString());
		        						    editor.commit();
		        						    
		        						    updateUserInfo(emailTextView.getText().toString(), passwordTextView.getText().toString(), fullNameTextView.getText().toString());
		        						    
		        						    mProgressDialog.dismiss();
	        								
		        							dialog.dismiss();
		        						    
		        							startActivity(new Intent(LoginActivity.this, HomeActivity.class));
		        							
		                   			}
				            }
				        });
				    }
				});
	            
	            return dialog;
	        }
	    }

	@SuppressLint("ValidFragment")
	public class ForgetPasswordDialogFragment extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            
        	final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View forgetPasswordLayout = inflater.inflate(R.layout.forget_password, null);
            
            final TextView emailTextView = (TextView) forgetPasswordLayout.findViewById(R.id.email);
            
            builder.setView(forgetPasswordLayout)
            	   .setTitle(R.string.password_reset)
            	   .setPositiveButton(R.string.reset_password, null)
	               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                    	   ForgetPasswordDialogFragment.this.getDialog().cancel();
                       }
                   });
            
            AlertDialog dialog = builder.create();
            
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
			    @Override
			    public void onShow(final DialogInterface dialog) {
			        Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
			        button.setOnClickListener(new View.OnClickListener() {
			            @Override
			            public void onClick(View view) {
			            	
			            	//check if the user has already logged in
			            	if(getLoginEmail() != null){
			            		
			            		runOnUiThread(new Runnable() {public void run() { 
        							dialog.dismiss();
        							startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    							}});
			            		
			            	}else{
			            		
			            		if((emailTextView.length() == 0) || (android.util.Patterns.EMAIL_ADDRESS.matcher(emailTextView.getText().toString()).matches() == false)){
			            				emailTextView.setError(getResources().getString(R.string.invalid_email));
			            			}
			            		else{
			            		
			            			mProgressDialog.show();
				        			
				        			mAmmWebService.getUser(emailTextView.getText().toString(), new BasicAsyncCallback() {

				        				public void onComplete(final WebserviceObject[] result, final Object state) {

				        					User userInfo = (User) result[0];
				        					
				        					if(userInfo != null){
				        						
				        						boolean resetUserPassword = false;
				        						
				        						try {
				        							resetUserPassword = (boolean) mAmmWebService.resetUserPassword(emailTextView.getText().toString());
				        						} catch (HttpClientException e) {
				        							Log.w("AMM HttpClientException:", e.getMessage());
				        						} catch (IOException e) {
				        							Log.w("AMM IOException:", e.getMessage());
				        						} catch (WebServiceException e) {
				        							Log.w("AMM WebServiceException:", e.getMessage());
				        						}
				        						
				        						if(resetUserPassword){
				        										        							
				        							runOnUiThread(new Runnable() {public void run() { 
				        								
				        								mProgressDialog.dismiss();
				        								
					        							dialog.dismiss();
					        							
					        							alertMessage(R.string.password_reset_success_message);
				        							}});
				        							
				        						}else{
				        							runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
				        							alertMessage(R.string.password_reset_error);
				        						}
				        						
				        						
				        						
				        					}else{
				        						runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
				        						alertMessage(R.string.account_not_found);
				        					}
				        				}

				        				public void onHttpClientException(final HttpClientException e, final Object state) {
				        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
				        					Log.w("AMM HttpClientException:", e.getMessage());
				        				}
				        				
				        				public void onIOException(final IOException e, final Object state) {
				        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
				        					Log.w("AMM IOException:", e.getMessage());
				        				}

				        				public void onWebServiceException(final WebServiceException e, final Object state) {
				        					runOnUiThread(new Runnable() {public void run() { mProgressDialog.dismiss(); }});
				        					Log.w("AMM WebServiceException:", e.getMessage());
				        					alertMessage(R.string.account_not_found);
				        				}

				        			}, null);
			            			
			            		}
			            	}
			            }
			        });
			    }
			});
            
            return dialog;
        }
    }
}
